package org.lql.algo.codecrush.week009.question.type.III;

import org.lql.algo.common.TreeNode;

/**
 * @author: liangqinglong
 * @date: 2025-08-20 16:58
 * @description: LCR 176. 判断是否为平衡二叉树 <a href="https://leetcode.cn/problems/ping-heng-er-cha-shu-lcof/description/">...</a>
 **/
public class IsBalanced {

	public boolean isBalanced(TreeNode root) {
		return height(root) != -1;
	}


	// 递归函数：返回子树高度，如果不平衡返回 -1
	private int height(TreeNode node) {
		if (node == null) {
			return 0;
		}

		int left = height(node.left);
		if (left == -1) {
			return -1;  // 左子树不平衡
		}

		int right = height(node.right);
		if (right == -1) {
			return -1; // 右子树不平衡
		}

		if (Math.abs(left - right) > 1) {
			return -1; // 当前节点不平衡
		}

		return Math.max(left, right) + 1; // 返回当前节点高度
	}

	public static void main(String[] args) {
		IsBalanced isBalanced = new IsBalanced();
		TreeNode root = new TreeNode(1);
		root.left = new TreeNode(2);
		root.right = new TreeNode(3);
		System.out.println(isBalanced.isBalanced(root));

	}
}
